<?php

namespace app\api\controller;


class Hosporder
{
    private $pagesize = 10;
    public $notice_url = "http://api.dongshuimian.com/api/hosporder/notify";//微信支付回调地址


//    public $notice_url = "http://api.witsleep.com/api/hosporder/notify";//微信支付回调地址

    public function refnotify()
    {
        (new \app\admin\model\Debug())->add([
                'txt' => json_encode($_REQUEST, true),
                'ty' => 8888,
                'ctime' => date("Y-m-d H:i:s")
            ]
        );
    }

    public function notify()
    {
        $input = file_get_contents('php://input');
        $isxml = true;
        if (!empty($input) && empty($_GET['out_trade_no'])) {
            $obj = isimplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
            $data = json_decode(json_encode($obj), true);
            if (empty($data)) {
                $result = array(
                    'return_code' => 'FAIL',
                    'return_msg' => ''
                );
                echo array2xml($result);
                exit;
            }
            if ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS') {
                $result = array(
                    'return_code' => 'FAIL',
                    'return_msg' => empty($data['return_msg']) ? $data['err_code_des'] : $data['return_msg']
                );
                echo array2xml($result);
                exit;
            }
            $get = $data;
        } else {
            $isxml = false;
            $get = $_GET;
        }

        $result_code = $get["result_code"];
        $out_trade_no = $get["out_trade_no"];
        $total_fee = $get["total_fee"] * 0.01;
        $transaction_id = $get["transaction_id"];
        $trade_no = $transaction_id;

        if ($result_code != "SUCCESS") {

            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => ''
            );
            echo array2xml($result);
            exit;
        }

        $hospOrder = new \app\admin\model\HospOrder();
        $order_info = $hospOrder->getDataForWhere(array('order_sn' => $out_trade_no));

        if (empty($order_info)) {
            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => ''
            );
            echo array2xml($result);
            exit;
        }

        //获取小程序配置信息
        $Config = config('WEIXIN_APP');
        $Config = $Config[$order_info['hosp_id']];
        $Config = $Config['userClient'];


        $appid = $Config['APPID'];
        $secret = $Config['APPSECRET'];
        $mch_id = $Config['MCHID'];
        $key = $Config['WXKEY'];
        $openid = $get["openid"];


        if ($appid != $get["appid"]) {

            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => ''
            );
            echo array2xml($result);
            exit;
        }


        if ($order_info['stat'] > 0) {
            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => ''
            );
            echo array2xml($result);
            exit;
        }


        if ($order_info['money'] > $total_fee) {
            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => ''
            );
            echo array2xml($result);
            exit;
        }

        $time = time();
        $updatData = array(
            'thread_no' => $trade_no,
            'stat' => 1,
            'status' => 1,
            'ptime' => $time,
        );
        $hospOrder->updateDataForWhere($updatData, array(
            'id' => $order_info['id']
        ));

        $config = getHospInfoConf();
        $doctor_order_over_time_no_confirm = $config['hospConfig']['doctor_order_over_time_no_confirm']['varvalue'];

        $this->addCancel($order_info['order_sn'], $doctor_order_over_time_no_confirm);
        addOrderTrackLog(array(
            'ctime' => date("Y-m-d H:i:s"),
            'order_sn' => $order_info['order_sn'],
            'op_uid' => 0,
            'op_username' => "",
            'act' => "微信支付成功",
        ));
        //判断是否开启了自动接单交互问诊 和快速问诊
        $this->systemDoctorAutoConfirmOrder($order_info['order_sn']);
        $result = array(
            'return_code' => 'SUCCESS',
            'return_msg' => 'OK'
        );
        echo array2xml($result);
    }
    public  function dd(){
        $hospOrder = new \app\admin\model\HospOrder();
        $order_info = $hospOrder->getDataForWhere(array('order_sn' => 'h2020052155985350'));

        $this->addDoctorOrderWarn("okaQw5aCwyi3RyDSzqR5aFKfRpuQ",$order_info,"已接单",1);
    }

    /**
     * 新增医生有新的问诊提醒
     * @param $order_sn
     * @param string $time
     */
    public function addDoctorOrderWarn($openid,$order_info,$memo, $time = "1")
    {
        $templateID = "sckWi5lmo-0bVCybOycEwViV5hYi2lNcu1JdmSEiXoA";
        $page = "/pages/index/index";
        $hosp_id = $order_info['hosp_id'];
        $client = 2;
        $miniprogram_state = "formal";
        $date=date("Y-m-d H:i:s");

        $sex="女";
        if($order_info['uid_sex']==1)
        {
            $sex="男";
        }
        $service="";
        if($order_info['ty']==1)
        {
            $service="快速问诊";
        }else  if($order_info['ty']==2)
        {
            $service="交互问诊";
        }
        $templateData = '{
           "thing1": {
             "value": "' .$order_info['uid_name'] ." ".$sex." ".$order_info['uid_birth']. '"
         },
         "thing2": {
             "value":"' . $order_info['contents'] . '"
         },
         "thing4": {
             "value": "' . $service . '"
         },
         "thing5": {
             "value": "' . $memo. '"
         },
         "date3": {
             "value": "' . $date . '"
         }
     }';
        $data=array(
            'openid'=>$openid,
            'order_sn'=>$order_info['order_sn'],
            'templateID'=>$templateID,
            'page'=>$page,
            'hosp_id'=>$hosp_id,
            'client'=>$client,
            'miniprogram_state'=>$miniprogram_state,
            'template_data'=>$templateData
        );

        $model = new \app\admin\model\SystemTask();
        $systemTask = array(
            'task_name' => '通知医生有新的问诊',
            'task_desc' => '通知医生有新的问诊',
            'task_fun' => '\app\api\controller\Hosporder#addDoctorOrderWarnTask',
            'task_param' => json_encode($data,true),
            'ctime' => date("Y-m-d H:i:s"),
            'stats' => '1',
            'task_type' => '0',
            'is_delete' => '0',
            'task_type' => '0',
        );
        if (!empty($time)) {
            $systemTask['stats'] = 0;
            $systemTask['task_type'] = 1;
            $systemTask['time_val'] = date("Y-m-d H:i:s", strtotime("+" . $time . "minutes"));
        }

        $insertID = $model->add($systemTask);
        if ($insertID) {
            $systemTask['id'] = $insertID;
            if (empty($time)) {//为0才立即执行
                addTaskQueue($systemTask);//添加app推送队列
            }
        }
    }

    public function addDoctorOrderWarnTask($param)
    {
        $res = wechatSendSubscribeTemplateMsg($param['hosp_id'], $param['client'], $param['openid'],
            $param['templateID'], $param['page'], $param['miniprogram_state'], $param['template_data']);
        if($res['err'])
        {
            addTaskLog(array(
                'taskname' => $param['order_sn'],
                'key' => time(),
                'param' => json_encode($param,true),
                'result' => "ok",
                'ctime' => date("Y-m-d H:i:s"),
            ));
            return 0;
        }else{
            addTaskLog(array(
                'taskname' => $param['order_sn'],
                'key' => time(),
                'param' => json_encode($param,true),
                'result' => $res['msg'],
                'ctime' => date("Y-m-d H:i:s"),
            ));
            return 1;
        }
    }

    /**
     * 支付成功后 系统自动接单
     * @param $order_sn
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function systemDoctorAutoConfirmOrder($order_sn)
    {
        $rdata = array('err' => 1, 'msg' => "");

        $hospOrder = new \app\admin\model\HospOrder();
        $order_info = $hospOrder->getDataForWhere(array('order_sn' => $order_sn));
        if (empty($order_info)) {
            return ['err' => 1, 'msg' => '订单不存在'];
        }
        if (empty($order_info['doctor_id'])) {
            return ['err' => 1, 'msg' => '未指定医生'];
        }
        $doctorInfo = getDoctorInfo($order_info['doctor_id']);
        if (empty($doctorInfo)) {
            return ['err' => 1, 'msg' => '医生信息不存在'];
        }

        if ($order_info['ty'] == 1) {
            if ($doctorInfo['is_open_fast'] == 0) {
                return ['err' => 1, 'msg' => '医生未开启自动接单'];
            }

            if ($doctorInfo['is_open'] == 0) {
                return ['err' => 1, 'msg' => '医生未开启接单'];
            }

        } else if ($order_info['ty'] == 2) {
            if ($doctorInfo['is_open_multi'] == 0) {
                return ['err' => 1, 'msg' => '医生未开启自动接单'];
            }
            if ($doctorInfo['is_open'] == 0) {
                return ['err' => 1, 'msg' => '医生未开启接单'];
            }
        }

        if ($order_info['stat'] <= 0) {
            return ['err' => 1, 'msg' => '订单未付款'];
        }
        if ($order_info['status'] <= 0) {
            return ['err' => 1, 'msg' => '订单未付款'];
        }
        if ($order_info['status'] == 2) {
            return ['err' => 1, 'msg' => '订单已经接诊'];
        }
        if ($order_info['status'] == 3) {
            return ['err' => 1, 'msg' => '订单已经待评价'];
        }
        if ($order_info['status'] == 4) {
            return ['err' => 1, 'msg' => '订单已经完成'];
        }
        if ($order_info['status'] == 5) {
            return ['err' => 1, 'msg' => '订单已经取消'];
        }


        $res = $hospOrder->updateDataForWhere(
            array('status' => 2, 'receipttime' => time()),
            array('id' => $order_info['id'])
        );
        if ($res || $res === 0) {

            $this->addAutoCloseZXTask($order_info['order_sn'], $order_info['ask_hours'] * 60);//多长时间内没有完成咨询，系统自动完成咨询 分钟内没有支付 关闭订单
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $order_info['order_sn'],
                'op_uid' => $doctorInfo['uid'],
                'op_username' => $doctorInfo['name'],
                'act' => "订单已被接单",
            ));
            if ($doctorInfo['start_msg']) {
                $this->systemAutoSendMsgToUser($order_info['order_sn'], $order_info['doctor_id'], $order_info['uid'], $order_info['hosp_id'], $doctorInfo['start_msg']);
            }
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }

    private function wxPay($openid, $order_sn, $total_fee, $body = "询诊费", $hosp_id = 0)
    {
        //获取小程序配置信息

        $Config = config('WEIXIN_APP');
        $Config = $Config[$hosp_id];
        $Config = $Config['userClient'];

        $appid = $Config['APPID'];
        $secret = $Config['APPSECRET'];
        $mch_id = $Config['MCHID'];
        $key = $Config['WXKEY'];

        $total_fee = floatval($total_fee * 100);
        include(dirname(realpath(APP_PATH)) . "/vendor/myCal/WxAppPay.php");
        $weixinpay = new \WxAppPay($appid, $openid, $mch_id, $key, $order_sn, $body, $total_fee);
        $weixinpay->setNoticeUrl($this->notice_url);//设置回调地址
        $return = $weixinpay->pay();
        if ($return['package']) {
            $preID = substr($return['package'], 10);
            (new \app\admin\model\HospOrder())->updateDataForWhere(array('prepay_id' => $preID), ['order_sn' => $order_sn]);
        }
        return $return;
    }

    //支付
    private function pay($openid, $orderInfo)
    {

        if ($orderInfo['is_delete'] == 1) {
            $return['err'] = 10009;
            $return['msg'] = '订单已经删除';
            return $return;
        }

        if ($orderInfo['status']) {
            $return['err'] = 10009;
            $return['msg'] = '订单已支付';
            return $return;
        }
        $rdata = $this->wxPay($openid, $orderInfo['order_sn'], $orderInfo['money'], '询诊费', $orderInfo['hosp_id']);

        $return['err'] = 0;
        $return['msg'] = "操作成功";
        $return['data'] = $rdata;
        return $return;
    }


    /**
     * 快速问诊下单接口
     *
     */
    public function addFastOrder()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        //获取配置金额
        $config = getHospSysConfig();
        $money = $config['one_ask_money']['varvalue'];
        $js_lv = $config['js_lv']['varvalue'];
        $ask_num = $config['one_ask_num']['varvalue'];
        $ask_hours = $config['one_ask_hours']['varvalue'];
        $data = array(
            'order_sn' => "h" . build_order_no(),
            'uid' => $userInfo['id'],
            'hosp_id' => $_hosp,
            'money' => $money,
            'ty' => 1,//问诊类型 1报告问诊  2、咨询问诊
            'pay_type' => 1,
            'ctime' => time(),
            'js_lv' => $js_lv,
            'ask_num' => $ask_num,
            'ask_hours' => $ask_hours,
        );

        $orderModel = new \app\admin\model\HospOrder();
        $res = $orderModel->add($data);
        if ($res) {
            $data['id'] = $res;
            $rdata = [];
            if ($data['money'] > 0) {
                $rdata = $this->pay($access_token, $data);
            }
            if ($rdata['err'] == 0) {
                $return['err'] = 0;
                $return['msg'] = '操作成功';
                $return['data'] = array(
                    'orderInfo' => array(
                        'order_sn' => $data['order_sn'],
                        'money' => $data['money']
                    ),
                    'payInfo' => $rdata
                );

                $config = getHospInfoConf();
                $order_over_time_no_pay = $config['hospConfig']['order_over_time_no_pay']['varvalue'];
                $this->addRunTask($data['order_sn'], $order_over_time_no_pay);//30分钟内没有支付 关闭订单
                addOrderTrackLog(array(
                    'ctime' => date("Y-m-d H:i:s"),
                    'order_sn' => $data['order_sn'],
                    'op_uid' => $userInfo['id'],
                    'op_username' => $userInfo['nickname'],
                    'act' => "创建订单",
                ));
                return json($return);
            } else {
                return json($rdata);
            }

        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }

    /**
     * 订单支付成功后，如果超过一定时间 都没有医生抢单 或者确认 就取消订单，并退款
     * @param $order_sn
     * @param string $time
     */
    public function addCancel($order_sn, $time = "0")
    {
        $model = new \app\admin\model\SystemTask();
        $systemTask = array(
            'task_name' => '订单' . $time . '分钟未抢单，就关闭订单',
            'task_desc' => '订单' . $time . '分钟未抢单，就关闭订单',
            'task_fun' => '\app\api\controller\Hosporder#closeOrderTaskTK',
            'task_param' => $order_sn,
            'ctime' => date("Y-m-d H:i:s"),
            'stats' => '1',
            'task_type' => '0',
            'is_delete' => '0',
            'task_type' => '0',
        );
        if (!empty($time)) {
            $systemTask['stats'] = 0;
            $systemTask['task_type'] = 1;
            $systemTask['time_val'] = date("Y-m-d H:i:s", strtotime("+" . $time . "minutes"));
        }

        $insertID = $model->add($systemTask);
        if ($insertID) {
            $systemTask['id'] = $insertID;
            if (empty($time)) {//为0才立即执行
                addTaskQueue($systemTask);//添加app推送队列
            }
        }
    }

    /**
     * 订单接单后，咨询超时，自动结束订单任务
     * @param $order_sn
     * @param string $time
     */
    public function addAutoCloseZXTask($order_sn, $time = "0")
    {
        $model = new \app\admin\model\SystemTask();
        $systemTask = array(
            'task_name' => '订单咨询超过' . $time . '分钟，结束咨询',
            'task_desc' => '订单咨询超过' . $time . '分钟，结束咨询',
            'task_fun' => '\app\api\controller\Hosporder#closeZXTask',
            'task_param' => $order_sn,
            'ctime' => date("Y-m-d H:i:s"),
            'stats' => '1',
            'task_type' => '0',
            'is_delete' => '0',
            'task_type' => '0',
        );
        if (!empty($time)) {
            $systemTask['stats'] = 0;
            $systemTask['task_type'] = 1;
            $systemTask['time_val'] = date("Y-m-d H:i:s", strtotime("+" . $time . "minutes"));
        }

        $insertID = $model->add($systemTask);
        if ($insertID) {
            $systemTask['id'] = $insertID;
            if (empty($time)) {//为0才立即执行
                addTaskQueue($systemTask);//添加app推送队列
            }
        }
    }


    public function addRunTask($order_sn, $time = "0")
    {
        $model = new \app\admin\model\SystemTask();
        $systemTask = array(
            'task_name' => '订单' . $time . '分钟未付款关闭订单任务',
            'task_desc' => '订单' . $time . '分钟未付款关闭订单任务',
            'task_fun' => '\app\api\controller\Hosporder#closeOrderTask',
            'task_param' => $order_sn,
            'ctime' => date("Y-m-d H:i:s"),
            'stats' => '1',
            'task_type' => '0',
            'is_delete' => '0',
            'task_type' => '0',
        );
        if (!empty($time)) {
            $systemTask['stats'] = 0;
            $systemTask['task_type'] = 1;
            $systemTask['time_val'] = date("Y-m-d H:i:s", strtotime("+" . $time . "minutes"));
        }

        $insertID = $model->add($systemTask);
        if ($insertID) {
            $systemTask['id'] = $insertID;
            if (empty($time)) {//为0才立即执行
                addTaskQueue($systemTask);//添加app推送队列
            }
        }
    }


    /**
     * 咨询超时自动 完成咨询订单
     * @param $order_sn
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function closeZXTask($order_sn)
    {
        $model = new \app\admin\model\HospOrder();
        $orderInfo = $model->getDataForWhere(array('order_sn' => $order_sn));
        if (empty($orderInfo)) {
            return 1000;
        }
        if ($orderInfo['stat'] > 1) {//说明已经退款 或者退款中
            return 1002;
        }
        if ($orderInfo['status'] == 5) {//说明已经退款 或者退款中
            return 1003;
        }
        if ($orderInfo['status'] == 3) {//说明已经完成了咨询
            return 1003;
        }
        if ($orderInfo['status'] == 4) {//说明已经完成了咨询 并完成了评价
            return 1003;
        }
        $doctorInfo = getDoctorInfo($orderInfo['doctor_id']);
        $res = $model->updateDataForWhere(array(
            'status' => 3,
            'closetime' => time()
        ), array('id' => $orderInfo['id']));
        if ($res || $res == 0) {
            if ($doctorInfo['end_msg']) {
                $this->systemAutoSendMsgToUser($orderInfo['order_sn'], $orderInfo['doctor_id'], $orderInfo['uid'], $orderInfo['hosp_id'], $doctorInfo['end_msg']);
            }
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => 0,
                'op_username' => "",
                'act' => "咨询超时，系统自动结束订单咨询",
            ));
            $config = getHospInfoConf();
            $this->addAutoCommentTask($orderInfo['order_sn'], $config['hospConfig']['order_auto_comment']['varvalue'] * 60);//30分钟内没有支付 关闭订单

            //增加医生的服务人数
            (new \app\admin\model\HospDoctor())->updateForInc(['uid' => $orderInfo['doctor_id']], 'service_num');
            return 0;
        } else {
            return 1003;
        }
    }

    public function addAutoCommentTask($order_sn, $time = "0")
    {
        $model = new \app\admin\model\SystemTask();
        $systemTask = array(
            'task_name' => '订单' . $time . '分钟后，自动评论',
            'task_desc' => '订单' . $time . '分钟后，自动评论',
            'task_fun' => '\app\api\controller\Hosporder#addAutoComment',
            'task_param' => $order_sn,
            'ctime' => date("Y-m-d H:i:s"),
            'stats' => '1',
            'task_type' => '0',
            'is_delete' => '0',
            'task_type' => '0',
        );
        if (!empty($time)) {
            $systemTask['stats'] = 0;
            $systemTask['task_type'] = 1;
            $systemTask['time_val'] = date("Y-m-d H:i:s", strtotime("+" . $time . "minutes"));
        }

        $insertID = $model->add($systemTask);
        if ($insertID) {
            $systemTask['id'] = $insertID;
            if (empty($time)) {//为0才立即执行
                addTaskQueue($systemTask);//添加app推送队列
            }
        }
    }

    /**
     * 关闭订单函数,超时未支付
     * @param $order_sn
     */
    public function closeOrderTask($order_sn)
    {
        $model = new \app\admin\model\HospOrder();
        $orderInfo = $model->getDataForWhere(array('order_sn' => $order_sn));
        if (empty($orderInfo)) {
            return 1000;
        }
        if ($orderInfo['stat'] > 0) {
            return 1002;
        }
        $res = $model->updateDataForWhere(array(
            'is_cancel' => 1,
            'canceltime' => time()
        ), array('id' => $orderInfo['id']));
        if ($res || $res == 0) {
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => 0,
                'op_username' => "",
                'act' => "取消订单，超时未支付订单",
            ));
            return 0;
        } else {
            return 1003;
        }
    }

    /**
     * 添加自动评论
     * @param $order_sn
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addAutoComment($order_sn)
    {
        $model = new \app\admin\model\HospOrder();
        $orderInfo = $model->getDataForWhere(array('order_sn' => $order_sn));
        if (empty($orderInfo)) {
            return 1000;
        }
        if ($orderInfo['stat'] <= 0) {
            return 1002;
        }

        if ($orderInfo['status'] <= 2) {
            return 1003;
        }
        if ($orderInfo['status'] == 4) {
            return 1004;
        }
        if ($orderInfo['status'] == 5) {
            return 1005;
        }

        $config = getHospInfoConf();
        $commentModel = new  \app\admin\model\HospComment();
        $data = array(
            'uid' => 0,
            'order_sn' => $orderInfo['order_sn'],
            'doctor_id' => $orderInfo['doctor_id'],
            'hosp_id' => $orderInfo['hosp_id'],
            'contents' => $config['hospConfig']['order_auto_comment']['varvalue']['info'],
            'score' => 5,
            'stats' => 0,
            'is_delete' => 0,
            'ctime' => time(),
        );

        $res = $commentModel->add($data);
        if ($res) {
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => 0,
                'op_username' => '',
                'act' => "对医生评论",
            ));
            //修改订单为已评价
            (new \app\admin\model\HospOrder())->updateDataForWhere(['status' => 4, 'pjtime' => time()], ['id' => $orderInfo['id']]);
            //计算好评率 和评价评分
            $this->updateDoctorData($orderInfo);
            return 0;
        } else {
            return 2;
        }
    }


    /**
     * 向指定医生问诊下单接口
     *
     */
    public function addOrder()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        $doctor_id = trim($_REQUEST['doctor_id']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        //查询医生信息

        $doctorUserInfo = $userModel->getID($doctor_id);

        if (empty($doctorUserInfo)) {
            $return['err'] = 1;
            $return['msg'] = '医生信息不存在';
            return json($return);
        }
        if (empty($doctorUserInfo['is_doctor'])) {
            $return['err'] = 1;
            $return['msg'] = '该用户还不是医生';
            return json($return);
        }
        $doctorModel = new \app\admin\model\HospDoctor();
        $doctorInfo = $doctorModel->getDataForWhere(array('tel' => $doctorUserInfo['uname']));
        if (empty($doctorUserInfo)) {
            $return['err'] = 1;
            $return['msg'] = '系统检查到该用户不是医生';
            return json($return);
        }


        //获取配置金额
        $config = getHospSysConfig();
        $money = $doctorInfo['service_price_now'];
        $js_lv = $config['js_lv']['varvalue'];
        $ask_num = $config['ask_num']['varvalue'];
        $ask_hours = $config['ask_hours']['varvalue'];
        $data = array(
            'order_sn' => "h" . build_order_no(),
            'uid' => $userInfo['id'],
            'doctor_id' => $doctorUserInfo['id'],
            'hosp_id' => $_hosp,
            'money' => $money,
            'ty' => 2,//问诊类型 1报告问诊  2、咨询问诊
            'pay_type' => 1,
            'ctime' => time(),
            'js_lv' => $js_lv,
            'ask_num' => $ask_num,
            'ask_hours' => $ask_hours,
        );

        $orderModel = new \app\admin\model\HospOrder();
        $res = $orderModel->add($data);
        if ($res) {
            $data['id'] = $res;
            $rdata = [];
            if ($data['money'] > 0) {
                $rdata = $this->pay($access_token, $data);
            }
            if ($rdata['err'] == 0) {
                $return['err'] = 0;
                $return['msg'] = '操作成功';
                $return['data'] = array(
                    'orderInfo' => array(
                        'order_sn' => $data['order_sn'],
                        'money' => $data['money']
                    ),
                    'payInfo' => $rdata
                );
                $config = getHospInfoConf();
                $order_over_time_no_pay = $config['hospConfig']['order_over_time_no_pay']['varvalue'];

                $this->addRunTask($data['order_sn'], $order_over_time_no_pay);//30分钟内没有支付 关闭订单
                addOrderTrackLog(array(
                    'ctime' => date("Y-m-d H:i:s"),
                    'order_sn' => $data['order_sn'],
                    'op_uid' => $userInfo['id'],
                    'op_username' => $userInfo['nickname'],
                    'act' => "创建订单",
                ));
                return json($return);
            } else {
                return json($rdata);
            }

        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }


    public function add()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        $uid_sex = trim($_REQUEST['uid_sex']);//性别
        $uid_birth = trim($_REQUEST['uid_birth']);//出入年月
        $contents = trim($_REQUEST['contents']);//问诊留言
        $other_file = trim($_REQUEST['other_file']);//
        $near_file = trim($_REQUEST['near_file']);//
        $scope_type = trim($_REQUEST['scope_type']);//
        $scope_val = trim($_REQUEST['scope_val']);//
        $uid_name = trim($_REQUEST['uid_name']);//
        $is_other_doctor_advice = trim($_REQUEST['is_other_doctor_advice']);//
        if (empty($is_other_doctor_advice)) {
            $is_other_doctor_advice = 0;
        } else {
            $is_other_doctor_advice = 1;
        }
        $ty = trim($_REQUEST['ty']);//
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        if (empty($uid_name)) {
            $uid_name = $userInfo['nickname'];
        }
        if (empty($contents)) {
            $return['err'] = 10009;
            $return['msg'] = '问诊留言不能为空';
            echo json_encode($return, true);
            exit;
        }
        if (empty($scope_type)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误,scope_type';
            echo json_encode($return, true);
            exit;
        }
        $doctor_id = 0;
        if ($scope_type == 1) {
            if (empty($scope_val)) {
                $return['err'] = 10009;
                $return['msg'] = '请指定询诊医生';
                echo json_encode($return, true);
                exit;
            }
            $doctorUserInfo = $userModel->getID($scope_val);

            if (empty($doctorUserInfo)) {
                $return['err'] = 1;
                $return['msg'] = '医生信息不存在';
                return json($return);
            }
            if (empty($doctorUserInfo['is_doctor'])) {
                $return['err'] = 1;
                $return['msg'] = '该用户还不是医生';
                return json($return);
            }
            $doctorModel = new \app\admin\model\HospDoctor();
            $doctorInfo = $doctorModel->getDataForWhere(array('tel' => $doctorUserInfo['uname']));
            if (empty($doctorUserInfo)) {
                $return['err'] = 1;
                $return['msg'] = '系统检查到该用户不是医生';
                return json($return);
            }
            if($doctorInfo['is_open']==0)
            {
                $return['err'] = 1;
                $return['msg'] = '医生已休息，暂不接诊';
                return json($return);
            }
            $doctor_id = $doctorInfo['uid'];

        }


        //查询医生信息

        //获取配置中医生等级配置
        $doctorLevelConfig = config("HOSPTIAL.doctor_level");
        $doctorLevelConfig = changeArrayKey($doctorLevelConfig, "id");
        //获取配置金额
        $config = getHospSysConfig();
        if ($ty == 2) {//交互问诊
            if ($scope_type == 1) {//指定医生
                $money = $doctorInfo['service_price_now'];
            } else {
                $money = $doctorLevelConfig[$doctorInfo['level']]['money'];
            }
            $js_lv = $config['js_lv']['varvalue'];
            $ask_num = $config['ask_num']['varvalue'];
            $ask_hours = $config['ask_hours']['varvalue'];
        } else if ($ty == 1) {//一次问诊 指定医生
            if ($scope_type == 1) {
                $money = $doctorInfo['fast_service_price_now'];
            } else {
                $tempScope_val = explode("|", $scope_val);
                if ($tempScope_val[0] == "-1") {
                    $money = $config['one_ask_money']['varvalue'];
                } else {
                    $money = $doctorLevelConfig[$tempScope_val[0]]['fast_money'];
                }
            }
            $js_lv = $config['js_lv']['varvalue'];
            $ask_num = $config['one_ask_num']['varvalue'];
            $ask_hours = $config['one_ask_hours']['varvalue'];
        }

        $data = array(
            'order_sn' => "h" . build_order_no(),
            'uid' => $userInfo['id'],
            'uid_name' => $uid_name,
            'doctor_id' => $doctor_id,
            'hosp_id' => $_hosp,
            'money' => $money,
            'ty' => $ty,//问诊类型 1报告问诊  2、咨询问诊
            'pay_type' => 1,
            'ctime' => time(),
            'js_lv' => $js_lv,
            'ask_num' => $ask_num,
            'ask_hours' => $ask_hours,
            'uid_sex' => $uid_sex,
            'uid_birth' => $uid_birth,
            'contents' => $contents,
            'other_file' => $other_file,
            'near_file' => $near_file,
            'scope_type' => $scope_type,
            'scope_val' => $scope_val,
            'is_other_doctor_advice' => $is_other_doctor_advice,
        );

        $orderModel = new \app\admin\model\HospOrder();
        $res = $orderModel->add($data);
        if ($res) {
            $data['id'] = $res;
            $rdata = [];
            if ($data['money'] > 0) {
                $rdata = $this->pay($access_token, $data);
            }
            if ($rdata['err'] == 0) {
                $return['err'] = 0;
                $return['msg'] = '操作成功';
                $return['data'] = array(
                    'orderInfo' => array(
                        'order_sn' => $data['order_sn'],
                        'money' => $data['money']
                    ),
                    'payInfo' => $rdata
                );
                $config = getHospInfoConf();
                $order_over_time_no_pay = $config['hospConfig']['order_over_time_no_pay']['varvalue'];
                $this->addRunTask($data['order_sn'], $order_over_time_no_pay);//30分钟内没有支付 关闭订单
                addOrderTrackLog(array(
                    'ctime' => date("Y-m-d H:i:s"),
                    'order_sn' => $data['order_sn'],
                    'op_uid' => $userInfo['id'],
                    'op_username' => $userInfo['nickname'],
                    'act' => "创建订单",
                ));
                return json($return);
            } else {
                return json($rdata);
            }

        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }


    public function againPay()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);

        $order_sn = trim($_REQUEST['order_sn']);//
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }


        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(array('order_sn' => $order_sn));
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['stat'] == 1) {
            $return['err'] = 10009;
            $return['msg'] = '订单已经支付';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['stat'] > 0) {
            $return['err'] = 10009;
            $return['msg'] = '不能支付该订单';
            echo json_encode($return, true);
            exit;
        }


        if ($orderInfo['is_cancel'] > 0) {
            $return['err'] = 10009;
            $return['msg'] = '订单支付超时，已经自动关闭';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['money'] <= 0) {
            $return['err'] = 1;
            $return['msg'] = '订单无需支付';
            echo json_encode($return, true);
            exit;
        }
        $rdata = $this->pay($access_token, $orderInfo);
        if ($rdata['err'] == 0) {
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            $return['data'] = array(
                'orderInfo' => array(
                    'order_sn' => $orderInfo['order_sn'],
                    'money' => $orderInfo['money']
                ),
                'payInfo' => $rdata
            );
            return json($return);
        } else {
            return json($rdata);
        }
    }


    /**
     * 医生端 我的患者 订单列表
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function doctorOrderlists()
    {
        $access_token = trim($_REQUEST['access_token']);
        $s_ty = trim($_REQUEST['s_ty']);//1待接诊  2接诊中
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        if (empty($s_ty)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        if (!in_array($s_ty, [1, 2])) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }

        $w = array('is_delete' => 0, 'is_cancel' => 0, 'hosp_id' => $_hosp);
        $orderby = "id desc";
        switch ($s_ty) {

            case 1:
                $w['doctor_id'] = $userInfo['id'];
                $w['status'] = 1;
                $w['stat'] = 1;
                $orderby = "ptime desc";
                break;
            case 2:
                $w['doctor_id'] = $userInfo['id'];
                $w['status'] = 2;
                $orderby = "receipttime desc";
                break;
        }
        $model = new \app\admin\model\HospOrder();
        $lists = $model->lists($w, $this->pagesize, '*', $orderby);

        foreach ($lists['data'] as $key => $val) {
            $lists['data'][$key] = $this->changeOrderTime($val);
            $lists['data'][$key]['ptimeString'] = toCurrTime($val['ptime']);
            $lists['data'][$key]['noReadmsgCount'] = 0;//患者给我的未读消息数量
            if ($val['status'] == 2) {
                $lists['data'][$key]['noReadmsgCount'] = getDcotorMsgNumNoRead($val);
            }
        }
        $lists['data'] = changeUidToUserinfoForLists($lists['data'], 'uid', '', 'id,uname,nickname,head,sex,bday,height,weight,ctime,money,level,vip,sleep_option,cid');

        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $lists;
        return json($return);
    }

    /**
     * 医生端
     *  医生获取订单列表【患者广场】  1可以接单  2 已失效
     */
    public function lists()
    {
        $access_token = trim($_REQUEST['access_token']);
        $s_ty = trim($_REQUEST['s_ty']);//1、可接单    2已失效
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        if (empty($s_ty)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        if (!in_array($s_ty, [1, 2])) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }

        $w = array('is_delete' => 0, 'is_cancel' => 0, 'hosp_id' => $_hosp);
        $orderby = "id desc";
        switch ($s_ty) {

            case 1:
                $w['doctor_id'] = 0;
                $w['status'] = 1;
                $w['stat'] = 1;
                $orderby = "ptime desc";
                break;
            case 2:
                $w['status'] = 5;
                $orderby = "canceltime1 desc";
                break;

        }
        $model = new \app\admin\model\HospOrder();
        $lists = $model->lists($w, $this->pagesize, '*', $orderby);

        foreach ($lists['data'] as $key => $val) {
            $lists['data'][$key] = $this->changeOrderTime($val);
            $lists['data'][$key]['ptimeString'] = toCurrTime($val['ptime']);
        }
        $lists['data'] = changeUidToUserinfoForLists($lists['data'], 'uid', '', 'id,uname,nickname,head,sex,bday,height,weight,ctime,money,level,vip,sleep_option,cid');

        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $lists;
        return json($return);
    }


    /**
     * 医生端 获取订单详情接口
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function doctorOrderInfo()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }
        if (in_array($orderInfo['status'], [2, 3, 4, 5])) {
            if ($orderInfo['doctor_id'] != $userInfo['id']) {
                $return['err'] = 10009;
                $return['msg'] = '您无权查看该订单';
                echo json_encode($return, true);
                exit;
            }
        }

        $orderInfo['UserInfo'] = getUserInfoForID($orderInfo['uid'], 'id,uname,nickname,head,sex,bday,height,weight,ctime,money,level,vip,sleep_option,cid');
        $doctorModel = new \app\admin\model\HospDoctor();
        $orderInfo['DoctorInfo'] = array();
        if ($orderInfo['doctor_id']) {
            $orderInfo['DoctorInfo'] = $doctorModel->getDataForWhere(array('uid' => $orderInfo['doctor_id']));
        }

        if ($orderInfo['DoctorInfo']) {
            $orderInfo['DoctorInfo'] = changeToDoctor($orderInfo['DoctorInfo']);
        }
        $orderInfo['adviceLists'] = array();
        if ($orderInfo['is_other_doctor_advice'])//可以查看其它医生开的医嘱
        {
            $orderInfo['adviceLists'] = $this->getHistoryAdvice($orderInfo['uid'], 3);
            $orderInfo['adviceLists'] = changeDoctorInfoForLists($orderInfo['adviceLists'], 'uid');
        }

        //获取近期的报告数据
        $orderInfo['near_file_lists'] = array();
        if ($orderInfo['near_file']) {
            $orderInfo['near_file_lists'] = getNearFile($orderInfo['near_file']);
        }
        $return['err'] = 0;
        $return['msg'] = '成功';
        $return['data'] = $orderInfo;
        echo json_encode($return, true);
    }


    /**
     * 用户端 获取订单详情接口
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function OrderInfo()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }
        if (in_array($orderInfo['status'], [0, 1, 2, 3, 4, 5])) {
            if ($orderInfo['uid'] != $userInfo['id']) {
                $return['err'] = 10009;
                $return['msg'] = '您无权查看该订单';
                echo json_encode($return, true);
                exit;
            }
        }

        $orderInfo['UserInfo'] = getUserInfoForID($orderInfo['uid'], 'id,uname,nickname,head,sex,bday,height,weight,ctime,money,level,vip,sleep_option,cid');
        $doctorModel = new \app\admin\model\HospDoctor();
        $orderInfo['DoctorInfo'] = array();
        if ($orderInfo['doctor_id']) {
            $orderInfo['DoctorInfo'] = $doctorModel->getDataForWhere(array('uid' => $orderInfo['doctor_id']));
        }

        if ($orderInfo['DoctorInfo']) {
            $orderInfo['DoctorInfo'] = changeToDoctor($orderInfo['DoctorInfo']);
        }
//        $orderInfo['adviceLists'] = array();
//        if ($orderInfo['is_other_doctor_advice'])//可以查看其它医生开的医嘱
//        {
//            $orderInfo['adviceLists'] = $this->getHistoryAdvice($orderInfo['uid'], 3);
//            $orderInfo['adviceLists'] = changeDoctorInfoForLists($orderInfo['adviceLists'], 'uid');
//        }

        //获取近期的报告数据
        $orderInfo['near_file_lists'] = array();
        if ($orderInfo['near_file']) {
            $orderInfo['near_file_lists'] = getNearFile($orderInfo['near_file']);
        }
        $return['err'] = 0;
        $return['msg'] = '成功';
        $return['data'] = $orderInfo;
        echo json_encode($return, true);
    }

    public function doctorConfirm()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $doctorInfo = getDoctorInfo($userInfo['id']);
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 0) {
            $return['err'] = 10009;
            $return['msg'] = '订单待支付';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 2 || $orderInfo['status'] == 3 || $orderInfo['status'] == 4) {
            $return['err'] = 10009;
            $return['msg'] = '订单已经被抢单了';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 5) {
            $return['err'] = 10009;
            $return['msg'] = '订单已经被取消';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 1 && !empty($orderInfo['doctor_id'])) {
            if ($orderInfo['doctor_id'] != $userInfo['id']) {
                $return['err'] = 10009;
                $return['msg'] = '您不能操作该订单';
                echo json_encode($return, true);
                exit;
            }
        }
        $res = $orderModel->updateDataForWhere(['doctor_id' => $userInfo['id'], 'status' => 2, 'receipttime' => time()], ['id' => $orderInfo['id']]);
        if ($res) {
            $this->addAutoCloseZXTask($orderInfo['order_sn'], $orderInfo['ask_hours'] * 60);//多长时间内没有完成咨询，系统自动完成咨询 分钟内没有支付 关闭订单

            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => $userInfo['id'],
                'op_username' => $doctorInfo['name'],
                'act' => "医生已接单",
            ));
            if ($doctorInfo['start_msg']) {
                $this->systemAutoSendMsgToUser($orderInfo['order_sn'], $userInfo['id'], $orderInfo['uid'], $orderInfo['hosp_id'], $doctorInfo['start_msg']);
            }
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            echo json_encode($return, true);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            echo json_encode($return, true);
        }
    }

    /**
     * 医生手动结束问诊
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function closeOrder()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $doctorInfo = getDoctorInfo($userInfo['id']);

        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 0) {
            $return['err'] = 10009;
            $return['msg'] = '订单待支付';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 1) {
            $return['err'] = 10009;
            $return['msg'] = '订单待接诊';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 3) {
            $return['err'] = 10009;
            $return['msg'] = '订单已经结束';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 4) {
            $return['err'] = 10009;
            $return['msg'] = '订单已经结束';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 5) {
            $return['err'] = 10009;
            $return['msg'] = '订单已经取消';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['doctor_id'] != $userInfo['id']) {
            $return['err'] = 10009;
            $return['msg'] = '您不能操作该订单';
            echo json_encode($return, true);
            exit;
        }

        $res = $orderModel->updateDataForWhere(['doctor_id' => $userInfo['id'], 'status' => 3, 'closetime' => time()], ['id' => $orderInfo['id']]);
        if ($res) {
            if ($doctorInfo['end_msg']) {
                $this->systemAutoSendMsgToUser($orderInfo['order_sn'], $orderInfo['doctor_id'], $orderInfo['uid'], $orderInfo['hosp_id'], $doctorInfo['end_msg']);
            }
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => $userInfo['id'],
                'op_username' => $doctorInfo['name'],
                'act' => "订单咨询已结束",
            ));
            //增加医生的服务人数
            (new \app\admin\model\HospDoctor())->updateForInc(['uid' => $orderInfo['doctor_id']], 'service_num');
            //添加自动好评的任务
            $config = getHospInfoConf();
            $this->addAutoCommentTask($orderInfo['order_sn'], $config['hospConfig']['order_auto_comment']['varvalue'] * 60);//30分钟内没有支付 关闭订单
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            echo json_encode($return, true);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            echo json_encode($return, true);
        }
    }


    /**
     * 获取一个用户的 最近的几个医嘱
     * @param $uid
     * @param int $num
     */
    private function getHistoryAdvice($uid, $num = 3)
    {
        $model = new \app\admin\model\HospDoctorAdvice();
        $list = $model->getDataForWheres(['receive_uid' => $uid, 'is_delete' => 0, 'is_send' => 1], "*", "id desc", $num);
        foreach ($list as $key => $val) {
            $list[$key]['ctimeFormat'] = date("Y-m-d", $val['ctime']);
        }
        return $list;
    }

    /**
     * 询诊用户 获取我的订单列表
     */
    public function mylists()
    {
        $access_token = trim($_REQUEST['access_token']);
        $status = trim($_REQUEST['status']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $pagesize = trim(input("pagesize"));//每页条数

        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }

        $w = array('uid' => $userInfo['id'], 'is_delete' => 0, 'is_cancel' => 0, 'hosp_id' => $_hosp);
        switch ($status) {
            case 0:
                $w['status'] = 0;
                break;
            case 1:
                $w['status'] = 1;
                break;
            case 2:
                $w['status'] = 2;
                break;
            case 3:
                $w['status'] = 3;
                break;
            case 4:
                $w['status'] = 4;
                break;
        }
        $model = new \app\admin\model\HospOrder();
        $lists = $model->lists($w, $this->pagesize, '*', "id desc");


        foreach ($lists['data'] as $key => $val) {
            $lists['data'][$key] = $this->changeOrderTime($val);
            $lists['data'][$key]['DoctorInfo'] = changeToDoctor(getDoctorInfo($val['doctor_id']), false);

        }
        $return['err'] = 0;
        $return['msg'] = '获取成功';
        $return['data'] = $lists;
        return json($return);
    }

    /**
     * 计算距离发问的时间
     */


    private function changeOrderTime($orderInfo)
    {
        if ($orderInfo['ctime']) {
            $orderInfo['ctime'] = date("Y-m-d H:i:s", $orderInfo['ctime']);
        }
        if ($orderInfo['ptime']) {
            $orderInfo['ptime'] = date("Y-m-d H:i:s", $orderInfo['ptime']);
        }
        if ($orderInfo['applytime']) {
            $orderInfo['applytime'] = date("Y-m-d H:i:s", $orderInfo['applytime']);
        }
        if ($orderInfo['receipttime']) {
            $orderInfo['receipttime'] = date("Y-m-d H:i:s", $orderInfo['receipttime']);
        }
        if ($orderInfo['closetime']) {
            $orderInfo['closetime'] = date("Y-m-d H:i:s", $orderInfo['closetime']);
        }
        if ($orderInfo['pjtime']) {
            $orderInfo['pjtime'] = date("Y-m-d H:i:s", $orderInfo['pjtime']);
        }

        if ($orderInfo['js_time']) {
            $orderInfo['js_time'] = date("Y-m-d H:i:s", $orderInfo['js_time']);
        }
        if ($orderInfo['canceltime']) {
            $orderInfo['canceltime'] = date("Y-m-d H:i:s", $orderInfo['canceltime']);
        }
        return $orderInfo;
    }


    /**
     * 指定医生订单 医生在没有接单前 取消订单接口
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function doctorCancelConfirm()
    {
        $access_token = trim($_REQUEST['access_token']);
        $order_sn = trim($_REQUEST['order_sn']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号为空';
            echo json_encode($return, true);
            exit;
        }
        $doctorInfo = (new \app\admin\model\HospDoctor())->getDataForWhere(['uid' => $userInfo['id']]);

        $model = new \app\admin\model\HospOrder();
        $orderInfo = $model->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单信息不存在';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['stat'] == 0) {
            $return['err'] = 10009;
            $return['msg'] = '订单未支付';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 2) {
            $return['err'] = 10009;
            $return['msg'] = '订单已经接诊';
            echo json_encode($return, true);
            exit;
        }


        if ($orderInfo['status'] == 3) {
            $return['err'] = 10009;
            $return['msg'] = "订单已经完成";
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 4) {
            $return['err'] = 10009;
            $return['msg'] = "订单已经完成";
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 5) {
            $return['err'] = 10009;
            $return['msg'] = "订单已经取消";
            echo json_encode($return, true);
            exit;
        }


        if ($orderInfo['doctor_id'] != $userInfo['id']) {
            $return['err'] = 10009;
            $return['msg'] = "您无权操作该订单";
            echo json_encode($return, true);
            exit;
        }
        $res = $model->updateDataForWhere(
            array('status' => 5, 'stat' => 2, 'canceltime1' => time()),
            array('id' => $orderInfo['id'])
        );
        if ($res || $res === 0) {

            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => $userInfo['id'],
                'op_username' => $doctorInfo['name'],
                'act' => "医生取消接诊该订单",
            ));

            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }

    public function grabOrConfirm()
    {
        $access_token = trim($_REQUEST['access_token']);
        $order_sn = trim($_REQUEST['order_sn']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 2, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号为空';
            echo json_encode($return, true);
            exit;
        }
        $doctorInfo = (new \app\admin\model\HospDoctor())->getDataForWhere(['uid' => $userInfo['id']]);

        $model = new \app\admin\model\HospOrder();
        $orderInfo = $model->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单信息不存在';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['stat'] == 0) {
            $return['err'] = 10009;
            $return['msg'] = '订单未支付';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 1) {
            if ($orderInfo['ty'] == 2) {
                if ($orderInfo['doctor_id'] != $userInfo['id']) {
                    $return['err'] = 10009;
                    $return['msg'] = "您无权确认该订单";
                    echo json_encode($return, true);
                    exit;
                }
            }
        }
        if ($orderInfo['status'] == 2) {
            if ($orderInfo['ty'] == 1) {
                $return['err'] = 10009;
                $return['msg'] = "订单已被抢";
                echo json_encode($return, true);
                exit;
            } else if ($orderInfo['ty'] == 2) {
                if ($orderInfo['doctor_id'] != $userInfo['id']) {
                    $return['err'] = 10009;
                    $return['msg'] = "您无权确认该订单";
                    echo json_encode($return, true);
                    exit;
                } else {
                    $return['err'] = 10009;
                    $return['msg'] = "您已经确认了该订单";
                    echo json_encode($return, true);
                    exit;
                }
            }
        }
        if ($orderInfo['status'] == 3) {
            $return['err'] = 10009;
            $return['msg'] = "订单已被抢";
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 4) {
            $return['err'] = 10009;
            $return['msg'] = "订单已被抢";
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 5) {
            $return['err'] = 10009;
            $return['msg'] = "订单已经取消";
            echo json_encode($return, true);
            exit;
        }

        $res = $model->updateDataForWhere(
            array('doctor_id' => $userInfo['id'], 'status' => 2, 'receipttime' => time()),
            array('id' => $orderInfo['id'])
        );
        if ($res || $res === 0) {

            $this->addAutoCloseZXTask($orderInfo['order_sn'], $orderInfo['ask_hours'] * 60);//多长时间内没有完成咨询，系统自动完成咨询 分钟内没有支付 关闭订单
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => $userInfo['id'],
                'op_username' => $doctorInfo['name'],
                'act' => "订单已被接单",
            ));
            if ($doctorInfo['start_msg']) {
                $this->systemAutoSendMsgToUser($orderInfo['order_sn'], $userInfo['id'], $orderInfo['uid'], $orderInfo['hosp_id'], $doctorInfo['start_msg']);
            }
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }

    /**
     * 订单开始或者结束时自动给患者发送消息
     */
    private function systemAutoSendMsgToUser($order_sn, $doctor_id, $uid, $hosp_id, $msg)
    {
        (new \app\admin\model\HospMsg())->save([
            'hosp_id' => $hosp_id,
            'ctime' => time(),
            'order_sn' => $order_sn,
            'send_uid' => $doctor_id,
            'receive_uid' => $uid,
            'contents' => $msg,
            'is_read' => 0
        ]);
    }

    /**
     * 用户取消订单
     * @param $order_sn
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userCancelOrder()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }


        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }


        if ($orderInfo['uid'] != $userInfo['id']) {
            $return['err'] = 10009;
            $return['msg'] = '你无权操作该订单';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 0) {
            $return['err'] = 10009;
            $return['msg'] = "不能进行该操作";
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 2) {
            $return['err'] = 10009;
            $return['msg'] = "医生已经接诊，不能取消了";
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 3) {
            $return['err'] = 10009;
            $return['msg'] = "医生已经接诊，不能取消了";
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 4) {
            $return['err'] = 10009;
            $return['msg'] = "询诊已经完成，不能取消了";
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 5) {
            $return['err'] = 10009;
            $return['msg'] = "请不要重复操作";
            echo json_encode($return, true);
            exit;
        }
        $res = $orderModel->updateDataForWhere(array(
            'status' => 5,
            'stat' => 2,
            'applytime' => time(),
            'canceltime1' => time()
        ), array('id' => $orderInfo['id']));
        if ($res || $res == 0) {
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => 0,
                'op_username' => $userInfo['nickname'],
                'act' => "用户取消订单",
            ));
            //添加到退款列表中
            //走退款流程
            import("myCal.AsyncHook#class", VENDOR_PATH);
            \AsyncHook::hook(array($this, 'hospOrderPayRefund'), array($orderInfo['order_sn'],$orderInfo['money']));

            $return['err'] = 0;
            $return['msg'] = "操作成功";
            echo json_encode($return, true);
            exit;
        } else {
            $return['err'] = 10009;
            $return['msg'] = "操作失败";
            echo json_encode($return, true);
            exit;
        }
    }


    /**
     * 关闭订单 超时 医生未抢单
     * @param $order_sn
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function closeOrderTaskTK($order_sn)
    {
        $model = new \app\admin\model\HospOrder();
        $orderInfo = $model->getDataForWhere(array('order_sn' => $order_sn));
        if (empty($orderInfo)) {
            return 1000;
        }
        if ($orderInfo['stat'] == 0) {
            return 1002;
        }
        if ($orderInfo['status'] == 2) {
            return 1002;
        }
        if ($orderInfo['status'] == 3) {
            return 1002;
        }
        if ($orderInfo['status'] == 4) {
            return 1002;
        }
        if ($orderInfo['status'] == 5) {
            return 1002;
        }
        $res = $model->updateDataForWhere(array(
            'status' => 5,
            'stat' => 2,
            'canceltime1' => time()
        ), array('id' => $orderInfo['id']));
        if ($res || $res == 0) {
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => 0,
                'op_username' => "",
                'act' => "取消订单，超时医生未抢单或者确认订单",
            ));
            //退款
            import("myCal.AsyncHook#class", VENDOR_PATH);
            \AsyncHook::hook(array($this, 'hospOrderPayRefund'), array($orderInfo['order_sn'],$orderInfo['money']));
            return 0;
        } else {
            return 1003;
        }
    }

    /**
     * 退款
     * @param $order_sn
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hospOrderPayRefund($order_sn, $tk_money = 0)
    {
        addOrderTrackLog(array(
            'ctime' => date("Y-m-d H:i:s"),
            'order_sn' => $order_sn,
            'op_uid' => 0,
            'op_username' => "",
            'act' => "发起退款[" . $tk_money . "]元",
        ));
        $res = hospOrderPayRefund($order_sn, $tk_money);
        if ($res['err'] == 0) {
            $model = new \app\admin\model\HospOrder();
            $model->updateDataForWhere(array(
                'stat' => 3,
            ), array('order_sn' => $order_sn));
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $order_sn,
                'op_uid' => 0,
                'op_username' => "",
                'act' => "退款成功",
            ));
        } else {
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $order_sn,
                'op_uid' => 0,
                'op_username' => "",
                'act' => "退款失败[" . $res['msg'] . "]",
            ));
        }
    }


    /**
     * 用户对询诊进行评价
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function comment()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token, 1, $_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['uid'] != $userInfo['id']) {
            $return['err'] = 10009;
            $return['msg'] = '无权操作';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['stat'] < 1) {
            $return['err'] = 10009;
            $return['msg'] = '订单未支付';
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 1) {
            $return['err'] = 10009;
            $return['msg'] = "订单还未接单";
            echo json_encode($return, true);
            exit;
        }
        if ($orderInfo['status'] == 2) {
            $return['err'] = 10009;
            $return['msg'] = "询诊还未结束";
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 4) {
            $return['err'] = 10009;
            $return['msg'] = "询诊已经完成";
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['status'] == 5) {
            $return['err'] = 10009;
            $return['msg'] = "询诊已经取消";
            echo json_encode($return, true);
            exit;
        }


        $contents = trim($_REQUEST['contents']);
        if (empty($contents)) {
            $return['err'] = 10009;
            $return['msg'] = '内容不能为空';
            echo json_encode($return, true);
            exit;
        }
        $score = trim($_REQUEST['score']);
        if (empty($score)) {
            $score = 0;
        }
        if ($score < 0 || $score > 5) {
            $return['err'] = 10009;
            $return['msg'] = '评分不正确';
            echo json_encode($return, true);
            exit;
        }
        $commentModel = new  \app\admin\model\HospComment();
        $data = array(
            'uid' => $userInfo['id'],
            'order_sn' => $orderInfo['order_sn'],
            'doctor_id' => $orderInfo['doctor_id'],
            'hosp_id' => $_hosp,
            'contents' => $contents,
            'score' => $score,
            'stats' => 0,
            'is_delete' => 0,
            'ctime' => time(),
        );

        $res = $commentModel->add($data);
        if ($res) {
            addOrderTrackLog(array(
                'ctime' => date("Y-m-d H:i:s"),
                'order_sn' => $orderInfo['order_sn'],
                'op_uid' => $userInfo['id'],
                'op_username' => $userInfo['nickname'],
                'act' => "对医生评论",
            ));
            //修改订单为已评价
            (new \app\admin\model\HospOrder())->updateDataForWhere(['status' => 4, 'pjtime' => time()], ['id' => $orderInfo['id']]);
            //计算好评率 和评价评分
            $this->updateDoctorData($orderInfo);
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }

    /**
     * 计算医生的好评率 和评分
     * @param $orderInfo
     */
    private function updateDoctorData($orderInfo)
    {
        $config = getHospInfoConf();
        $plSplitScore = $config['hospConfig']['good_comment_score']['varvalue'];

        $commentModel = new  \app\admin\model\HospComment();
        $av_score = $commentModel->getAvg(['doctor_id' => $orderInfo['doctor_id']], "score");
        $badNum = $commentModel->getCount(['doctor_id' => $orderInfo['doctor_id'], 'score' => array('lt', $plSplitScore)]);
        $goodNum = $commentModel->getCount(['doctor_id' => $orderInfo['doctor_id'], 'score' => array('egt', $plSplitScore)]);
        $score_lv = roundingE($goodNum / ($goodNum + $badNum), 2);
        (new \app\admin\model\HospDoctor())->updateDataForWhere(['score_lv' => $score_lv, 'av_score' => $av_score], ['uid' => $orderInfo['doctor_id']]);
    }




}

